package com.project.springboot.mongodb.multi.ds.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

@Configuration
@EnableConfigurationProperties(MultipleMongoProperties.class)
@EnableMongoRepositories(
	basePackages = "com.project.springboot.mongodb.multi.ds.repository.secondary",
	mongoTemplateRef = "secondaryMongoTemplate"
)
public class SecondaryMongoConfig {
	
	@Autowired
	private MultipleMongoProperties multipleMongoProperties;
	
	@Bean
	public MongoDbFactory secondaryFactory(MongoProperties properties) {
		MongoClient client = new MongoClient(new MongoClientURI(multipleMongoProperties.getSecondary().getUri()));
		return new SimpleMongoDbFactory(client, multipleMongoProperties.getSecondary().getDatabase());
	}
	
	@Bean
	@Qualifier("secondaryMongoTemplate")
	public MongoTemplate secondaryMongoTemplate() {
		return new MongoTemplate(secondaryFactory(multipleMongoProperties.getSecondary()));
	}
}
